package fun.wxy.camera.fragment;

import android.app.Activity;
import android.content.Context;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import fun.wxy.camera.R;

public class NfcReadFragment extends Fragment implements NfcAdapter.ReaderCallback {
    private static final String TAG = "NfcReader";
    private NfcAdapter nfcAdapter;
    private TextView textView;
    private Activity activity;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        activity = (Activity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_nfc_read, container, false);
        textView = view.findViewById(R.id.nfc_content);

        ImageView backBtn = view.findViewById(R.id.btn_back);
        backBtn.setOnClickListener(v -> requireActivity().getSupportFragmentManager().popBackStack());

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        initNFC();
        if (nfcAdapter != null) {
            nfcAdapter.enableReaderMode(activity, this,
                    NfcAdapter.FLAG_READER_NFC_A |
                            NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK,
                    null);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (nfcAdapter != null) {
            nfcAdapter.disableReaderMode(activity);
        }
    }

    private void initNFC() {
        nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
        if (nfcAdapter == null) {
            showToast("设备不支持NFC");
            return;
        }
        if (!nfcAdapter.isEnabled()) {
            showToast("请先启用NFC功能");
        }
    }

    @Override
    public void onTagDiscovered(Tag tag) {
        Log.d(TAG, "发现标签，技术列表: " + Arrays.toString(tag.getTechList()));

        activity.runOnUiThread(() ->
                textView.setText("发现标签，正在解析..."));

        // 尝试三种解析方式
        if (handleNdefTag(tag)) return;
        if (handleFormatableTag(tag)) return;
        handleOtherTagTypes(tag);
    }

    private boolean handleNdefTag(Tag tag) {
        Ndef ndef = Ndef.get(tag);
        if (ndef == null) return false;

        try {
            ndef.connect();
            NdefMessage message = ndef.getCachedNdefMessage();
            if (message != null) {
                String content = parseNdefMessage(message);
                updateUI("NDEF内容:\n" + content);
            } else {
                updateUI("空NDEF标签");
            }
            return true;
        } catch (IOException e) {
            showError(e);
            return false;
        } finally {
            try {
                ndef.close();
            } catch (IOException e) {
                Log.e(TAG, "关闭NDEF连接失败", e);
            }
        }
    }

    private boolean handleFormatableTag(Tag tag) {
        NdefFormatable formatable = NdefFormatable.get(tag);
        if (formatable == null) return false;

        try {
            formatable.connect();
            formatable.format(new NdefMessage(
                    new NdefRecord(NdefRecord.TNF_EMPTY, null, null, null)
            ));
            updateUI("标签已格式化为NDEF");
            return true;
        } catch (IOException | FormatException e) {
            showError(e);
            return false;
        } finally {
            try {
                formatable.close();
            } catch (IOException e) {
                Log.e(TAG, "关闭Formatable连接失败", e);
            }
        }
    }

    private void handleOtherTagTypes(Tag tag) {
        StringBuilder sb = new StringBuilder();
        sb.append("非NDEF标签\n");
        sb.append("UID: ").append(bytesToHex(tag.getId())).append("\n");
        sb.append("支持技术:\n");

        for (String tech : tag.getTechList()) {
            sb.append("- ").append(tech.substring(tech.lastIndexOf('.') + 1)).append("\n");
        }

        // 尝试读取NFC-A类型标签
        if (Arrays.asList(tag.getTechList()).contains(NfcA.class.getName())) {
            readNfcATag(tag, sb);
        }

        updateUI(sb.toString());
    }

    private void readNfcATag(Tag tag, StringBuilder sb) {
        NfcA nfcA = NfcA.get(tag);
        if (nfcA == null) return;

        try {
            nfcA.connect();
            byte[] response = nfcA.transceive(new byte[]{
                    (byte) 0x30,  // READ命令
                    (byte) 0x00    // 块地址
            });
            sb.append("\n块0数据: ").append(bytesToHex(response));
        } catch (IOException e) {
            sb.append("\n读取失败: ").append(e.getMessage());
        } finally {
            try {
                nfcA.close();
            } catch (IOException e) {
                Log.e(TAG, "关闭NfcA连接失败", e);
            }
        }
    }

    // NDEF解析工具方法
    private String parseNdefMessage(NdefMessage message) {
        StringBuilder sb = new StringBuilder();
        for (NdefRecord record : message.getRecords()) {
            String recordText = parseRecord(record);
            if (recordText != null) {
                sb.append(recordText).append("\n");
            }
        }
        return sb.toString().trim();
    }

    private String parseRecord(NdefRecord record) {
        try {
            if (record.getTnf() == NdefRecord.TNF_WELL_KNOWN) {
                if (Arrays.equals(record.getType(), NdefRecord.RTD_TEXT)) {
                    return parseTextRecord(record);
                } else if (Arrays.equals(record.getType(), NdefRecord.RTD_URI)) {
                    return parseUriRecord(record);
                }
            }
            return "未知类型记录";
        } catch (Exception e) {
            return "解析记录失败";
        }
    }

    private String parseTextRecord(NdefRecord record) throws Exception {
        byte[] payload = record.getPayload();
        String encoding = ((payload[0] & 0x80) == 0) ? "UTF-8" : "UTF-16";
        int langCodeLength = payload[0] & 0x3F;
        return new String(payload, langCodeLength + 1,
                payload.length - langCodeLength - 1, encoding);
    }

    private String parseUriRecord(NdefRecord record) throws Exception {
        byte[] payload = record.getPayload();
        String prefix = UriRecord.URI_PREFIX_MAP.get(payload[0]);
        return prefix + new String(payload, 1, payload.length - 1, "UTF-8");
    }

    // 工具方法
    private void updateUI(String text) {
        activity.runOnUiThread(() -> textView.setText(text));
    }

    private void showToast(String message) {
        activity.runOnUiThread(() ->
                Toast.makeText(activity, message, Toast.LENGTH_SHORT).show());
    }

    private void showError(Exception e) {
        Log.e(TAG, "NFC操作错误", e);
        updateUI("错误: " + e.getMessage());
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X ", b));
        }
        return sb.toString().trim();
    }

    // Uri前缀映射表
    private static class UriRecord {
        static final Map<Byte, String> URI_PREFIX_MAP = new HashMap<>();

        static {
            URI_PREFIX_MAP.put((byte) 0x00, "");
            URI_PREFIX_MAP.put((byte) 0x01, "http://www.");
            URI_PREFIX_MAP.put((byte) 0x02, "https://www.");
            URI_PREFIX_MAP.put((byte) 0x03, "http://");
            URI_PREFIX_MAP.put((byte) 0x04, "https://");
            // 其他前缀可根据需要扩展
        }
    }
}